/*******************************************************************************
 * Package: com.hngtrust.iir.news
 * Type:    NewsController
 * Date:    2021-3-16 20:24
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.news.controller;

import com.hngtrust.clickhouse.news.dto.ListRiskNewsReqDTO;
import com.hngtrust.clickhouse.news.dto.NewsCodeReqDTO;
import com.hngtrust.clickhouse.news.dto.NewsSentimentRespDTO;
import com.hngtrust.clickhouse.news.dto.QuerySentimentByNewsIdDTO;
import com.hngtrust.clickhouse.news.entity.AppNews;
import com.hngtrust.clickhouse.news.entity.AppNewsSentiment;
import com.hngtrust.clickhouse.news.service.AppNewsSentimentService;
import com.hngtrust.clickhouse.news.service.AppNewsService;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.entity.IndustrySw;
import com.hngtrust.iir.base.service.IndustrySwService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.news.controller.dto.*;
import com.hngtrust.iir.risk.entity.RiskMonitor;
import com.hngtrust.iir.risk.service.RiskMonitorService;
import com.hngtrust.iir.user.entity.CollectInfo;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.CollectInfoService;
import com.hngtrust.iir.user.service.TagRelService;
import com.hngtrust.iir.util.HtmlUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 新闻资讯
 * @author Chentianyong
 * @date 2021-3-16 20:24
 */
@Slf4j
@Api(tags = "新闻资讯")
@RestController
@RequestMapping("/news")
public class NewsController {
    
    @Autowired
    private AppNewsService appNewsService;
    
    @Autowired
    private TagRelService tagRelService;
    
    @Autowired
    private PageService pageService;

    @Autowired
    private IndustrySwService industrySwService;

    @Autowired
    private CollectInfoService collectInfoService;
    
    
    @Autowired
    private RiskMonitorService riskMonitorService;
    
    @Autowired
    private AppNewsSentimentService appNewsSentimentService;
    
    @Value("${tiger.minio.out.address}")
    private String minioAddress;
    
    
    @ApiOperation(value = "首页新闻列表")
    @PostMapping("/list-home-page-news")
    public ResponseInfo<List<ListNewsRespVO>> listHomePageNews(
            @ApiParam(value = "分页参数") @Valid @RequestBody ReqDTO req
    ){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        RiskMonitor monitor = new RiskMonitor();
        monitor.setCreateUserId(loginUser.getId());
        List<String> ids = riskMonitorService.queryList(monitor).stream().map(r -> r.getCompId().toString())
                .collect(Collectors.toList());
       
        List<String> newsIds = appNewsSentimentService.queryByCompId(ids).stream().map(a -> a.getNewsId())
                .collect(Collectors.toList());
        if (newsIds.isEmpty()){
            return new ResponseInfo<>();
        }
        ListRiskNewsReqDTO dto = new ListRiskNewsReqDTO();
        dto.setNewsId(newsIds);
        PageResult<AppNews> page = pageService.page(req.getPageParam(), () -> appNewsService.queryByIds( dto));
        List<ListNewsRespVO> news = new ArrayList<>();
        for (AppNews appNews :page.getRows()){
            ListNewsRespVO respDTO = new ListNewsRespVO();
            BeanUtils.copyProperties(appNews,respDTO);
            respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNews.getHtml(),minioAddress));
            TagRel tagRel = new TagRel();
                tagRel.setDataType(Constant.TAG_DATATYPE_NEWS);
            tagRel.setDataId(appNews.getId());
            List<TagRel> tagRels = tagRelService.queryList(tagRel);
            AppNewsSentiment sentiment = new AppNewsSentiment();
            sentiment.setNewsId(appNews.getId());
           
            
            respDTO.setLabels(tagRels);
            
            List<QuerySentimentByNewsIdDTO> dtos = appNewsSentimentService
                    .querySentimentByNewsId(appNews.getId());
            if (dtos.size() >10 ){
                dtos = dtos.subList(0,10);
            }
            respDTO.setCompNames(dtos);
            if(null != appNews.getSentiment()){
                if (Constant.SENTIMENT_POSITIVE.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("积极");
                }
                if (Constant.SENTIMENT_NEUTRAL.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("中立");
                }
                if (Constant.SENTIMENT_NEGATIVE.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("消极");
                }
            }
            news.add(respDTO);
        }
        PageResult<ListNewsRespVO> pageResult = new PageResult<>();
        pageResult.setRows(news);
        pageResult.setPage(page.getPage());
        return new ResponseInfo(pageResult);
    }
    /**
     * 根据公司id查询新闻
     */
    @ApiOperation("根据公司id查询新闻")
    @PostMapping("/query-compId")
    public ResponseInfo<PageResult<ListNewsRespVO>> queryByCompId(@ApiParam(value = "查询请求") @Valid @RequestBody ReqDTO<QueryByCompIdReqVO> req){
        log.info("查询公司id：：：：："+req.getContent().getCompId().toString());
        PageResult<AppNews> page = pageService.page(req.getPageParam(), () -> appNewsService.queryCompNews(req.getContent().getCompId().toString()));
        
        PageResult<ListNewsRespVO> pageResult = new PageResult<>();
        List<ListNewsRespVO> news = new ArrayList<>();
        for (AppNews appNews :page.getRows()){
            ListNewsRespVO respDTO = new ListNewsRespVO();
            BeanUtils.copyProperties(appNews,respDTO);
            respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNews.getHtml(),minioAddress));
            
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_NEWS);
            tagRel.setDataId(appNews.getId());
            List<TagRel> tagRels = tagRelService.queryList(tagRel);
            
            AppNewsSentiment sentiment = new AppNewsSentiment();
            sentiment.setNewsId(appNews.getId());
            
            respDTO.setLabels(tagRels);
           
            if(null != appNews.getSentiment()){
                if (Constant.SENTIMENT_POSITIVE.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("积极");
                }
                if (Constant.SENTIMENT_NEUTRAL.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("中立");
                }
                if (Constant.SENTIMENT_NEGATIVE.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("消极");
                }
            }
            List<QuerySentimentByNewsIdDTO> dtos = appNewsSentimentService
                    .querySentimentByNewsId(appNews.getId());
            if (dtos.size() >10 ){
                dtos = dtos.subList(0,10);
            }
            respDTO.setCompNames(dtos);
            news.add(respDTO);
        }
        
        pageResult.setRows(news);
        pageResult.setPage(page.getPage());
        return new ResponseInfo(pageResult);
    }
    
    @ApiOperation("最新新闻")
    @PostMapping("new-news")
    public ResponseInfo<PageResult<ListNewsRespVO>> newNews(@ApiParam("分页参数")  @RequestBody ReqDTO dto){
        PageResult<AppNews> page = pageService.page(dto.getPageParam(), () -> appNewsService.queryList(new AppNews()));
        List<ListNewsRespVO> news = new ArrayList<>();
        for (AppNews appNews :page.getRows()){
            ListNewsRespVO respDTO = new ListNewsRespVO();
            BeanUtils.copyProperties(appNews,respDTO);
            if(null != appNews.getHtml()){
                respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNews.getHtml(),minioAddress));
            }
            
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_NEWS);
            if(null != appNews.getId()){
                tagRel.setDataId(appNews.getId());
    
                List<TagRel> tagRels = tagRelService.queryList(tagRel);
    
                AppNewsSentiment sentiment = new AppNewsSentiment();
                if(null != appNews.getId()){
                    sentiment.setNewsId(appNews.getId());
                }
                
                if(null != appNews.getSentiment()){
                    if (Constant.SENTIMENT_POSITIVE.equals(appNews.getSentiment())) {
                        respDTO.setSentiment("积极");
                    }
                    if (Constant.SENTIMENT_NEUTRAL.equals(appNews.getSentiment())) {
                        respDTO.setSentiment("中立");
                    }
                    if (Constant.SENTIMENT_NEGATIVE.equals(appNews.getSentiment())) {
                        respDTO.setSentiment("消极");
                    }
                }
               
                
                respDTO.setLabels(tagRels);
                List<QuerySentimentByNewsIdDTO> dtos = appNewsSentimentService
                        .querySentimentByNewsId(appNews.getId());
                if (dtos.size() >10 ){
                    dtos = dtos.subList(0,10);
                }
                respDTO.setCompNames(dtos);
                news.add(respDTO);
            }
            
            
        }
        PageResult<ListNewsRespVO> pageResult = new PageResult<>();
        pageResult.setRows(news);
        pageResult.setPage(page.getPage());
        return new ResponseInfo(pageResult);
    }
    
    @ApiOperation("根据id查询")
    @PostMapping("/query-id")
    public ResponseInfo<ListNewsRespVO> queryById(@ApiParam(value = "公告id") @Valid @RequestBody QueryByNewsIdReqVO vo) {

        AppNews appNews = appNewsService.queryById(vo.getId());
        ListNewsRespVO respDTO = new ListNewsRespVO();
        if(appNews != null){
            BeanUtils.copyProperties(appNews,respDTO);
        }
        respDTO.setEmotionProport(appNews.getEmotionProport().setScale(2, RoundingMode.HALF_UP));
        if (appNews.getHtml()!=null && !appNews.getHtml().isEmpty()){
            String s = HtmlUtils.replaceHtmlTag(appNews.getHtml(), minioAddress);
            if (s.indexOf("&lt;")!= -1 && s.indexOf("&gt;")!=-1){
                s.replaceAll("&gt;",">").replaceAll("&lt;","<");
            }
            respDTO.setHtml(s);
        }
        
        TagRel tagRel = new TagRel();
        tagRel.setDataType(Constant.TAG_DATATYPE_NEWS);
        tagRel.setDataId(appNews.getId());
        List<TagRel> tagRels = tagRelService.queryList(tagRel);
        
        AppNewsSentiment sentiment = new AppNewsSentiment();
        sentiment.setNewsId(appNews.getId());
        
        if(null != appNews.getSentiment()){
            if (Constant.SENTIMENT_POSITIVE.equals(appNews.getSentiment())) {
                respDTO.setSentiment("积极");
            }
            if (Constant.SENTIMENT_NEUTRAL.equals(appNews.getSentiment())) {
                respDTO.setSentiment("中立");
            }
            if (Constant.SENTIMENT_NEGATIVE.equals(appNews.getSentiment())) {
                respDTO.setSentiment("消极");
            }
        }
        respDTO.setLabels(tagRels);
        List<QuerySentimentByNewsIdDTO> dtos = appNewsSentimentService
                .querySentimentByNewsId(appNews.getId());
        
        respDTO.setCompNames(dtos);
        respDTO.setInfoType(1);

        //是否已收藏
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        CollectInfo collect = new CollectInfo();
        collect.setInfoId(Long.getLong(vo.getId()));
        collect.setCreateUserId(loginUser.getId());
        List<CollectInfo> collectList = collectInfoService.queryList(collect);
        if(!collectList.isEmpty()){
            respDTO.setCollect(Constant.WHETHER_YES);
        }
        else{
            respDTO.setCollect(Constant.WHETHER_NO);
        }
        return new ResponseInfo<>(respDTO);
    }


    @ApiOperation("根据行业code查询二级行业类型的行业资讯")
    @PostMapping("/queryTwoNumNews-code")
    public ResponseInfo<List<NewsCodeRespVO>> queryTwoNewsByNumCode(@ApiParam(value = "行业code") @Valid @RequestBody NewsCodeReqVO vo) {
        log.info("NewsController.queryTwoNewsByNumCode start...");
        List<NewsCodeReqDTO> newsCodeReqDTOList = appNewsService.queryTwoByIndustryCode(vo.getCode().substring(0,2));
        IndustrySw industrySw = new IndustrySw();
        industrySw.setCode(vo.getCode().substring(0,2));
        industrySw.setLevel(2);
        List<IndustrySw> industrySwList = industrySwService.querySubList(industrySw);
        return getListResponseInfo(newsCodeReqDTOList, industrySwList);
    }

    private ResponseInfo<List<NewsCodeRespVO>> getListResponseInfo(List<NewsCodeReqDTO> newsCodeReqDTOList, List<IndustrySw> industrySwList) {
        List<NewsCodeRespVO> newsCodeRespVOList = getNewsCodeRespVOS(newsCodeReqDTOList,industrySwList);
        log.info("********newsCodeRespVOList的大小为***********："+newsCodeRespVOList.size());
        if(!newsCodeRespVOList.isEmpty()){
            newsCodeRespVOList = newsCodeRespVOList.stream().sorted((b, a) -> -a.getIndustryId().compareTo(b.getIndustryId())).collect(Collectors.toList());

        }
        return new ResponseInfo<>(newsCodeRespVOList);
    }

    @ApiOperation("根据行业code查询三级行业类型的行业资讯")
    @PostMapping("/queryThreeNumNews-code")
    public ResponseInfo<List<NewsCodeRespVO>> queryThreeNewsByIndustryCode(@ApiParam(value = "行业code") @Valid @RequestBody NewsCodeReqVO vo) {
        log.info("NewsController.queryThreeNewsByIndustryCode start...");
        List<NewsCodeReqDTO> newsCodeReqDTOList = appNewsService.queryThreeByIndustryCode(vo.getCode().substring(0,4));
        IndustrySw industrySw = new IndustrySw();
        industrySw.setCode(vo.getCode().substring(0,4));
        industrySw.setLevel(3);
        List<IndustrySw> industrySwList = industrySwService.querySubList(industrySw);
        return getListResponseInfo(newsCodeReqDTOList, industrySwList);
    }

    @ApiOperation("根据行业code查询四级行业类型的行业资讯")
    @PostMapping("/queryFourNumNews-code")
    public ResponseInfo<List<NewsCodeRespVO>> queryFourNewsByIndustryCode(@ApiParam(value = "行业code") @Valid @RequestBody NewsCodeReqVO vo) {
        log.info("NewsController.queryFourNewsByIndustryCode start...");
        List<NewsCodeReqDTO> newsCodeReqDTOList = appNewsService.queryFourByIndustryCode(vo.getCode().substring(0,6));
        IndustrySw industrySw = new IndustrySw();
        industrySw.setCode(vo.getCode().substring(0,6));
        industrySw.setLevel(4);
        List<IndustrySw> industrySwList = industrySwService.querySubList(industrySw);
        List<NewsCodeRespVO> newsCodeRespVOList = getNewsCodeRespVOS(newsCodeReqDTOList,industrySwList);
        log.info("********newsCodeRespVOList的大小为***********："+newsCodeRespVOList.size());
        if(!newsCodeRespVOList.isEmpty()){
            newsCodeRespVOList = newsCodeRespVOList.stream().sorted((b, a) -> -a.getCreateTime().compareTo(b.getCreateTime())).collect(Collectors.toList());

        }
        return new ResponseInfo<>(newsCodeRespVOList);
    }

    @ApiOperation("查询行业大类的行业资讯")
    @PostMapping("/queryAllNews-Industry")
    public ResponseInfo<List<NewsCodeRespVO>> queryAllNewsIndustry() {
        log.info("NewsController.queryAllNewsIndustry start...");
        List<NewsCodeReqDTO> newsCodeReqDTOList = appNewsService.queryAllIndustry();
        IndustrySw industrySw = new IndustrySw();
        industrySw.setLevel(1);
        List<IndustrySw> industrySwList = industrySwService.querySubListByOneLevel(industrySw);
        return getListResponseInfo(newsCodeReqDTOList, industrySwList);
    }

    //查询行业分类及其数量方法
    private List<NewsCodeRespVO> getNewsCodeRespVOS(List<NewsCodeReqDTO> newsCodeReqDTOList,List<IndustrySw> industrySwList) {
        List<NewsCodeRespVO> newsCodeRespVOList = new ArrayList<>();
        List<String> industryCode = new ArrayList<>();
        for(NewsCodeReqDTO newsCodeReqDTO : newsCodeReqDTOList){
            industryCode.add(newsCodeReqDTO.getIndustryCode());
        }
        for(IndustrySw indestrySw : industrySwList){
            if(!industryCode.contains(indestrySw.getCode())){
                NewsCodeRespVO newsCodeRespVO = new NewsCodeRespVO();
                IndustrySw industrySw = industrySwService.queryByCode(indestrySw.getCode());
                newsCodeRespVO.setNewsNum(0);
                newsCodeRespVO.setIndustryCode(indestrySw.getCode());
                newsCodeRespVO.setIndustryId(industrySw.getId());
                newsCodeRespVO.setIndustryName(industrySw.getName());
                newsCodeRespVO.setCreateTime(industrySw.getCreateTime());
                newsCodeRespVOList.add(newsCodeRespVO);
            }
        }

        for(NewsCodeReqDTO newsCodeReqDTO : newsCodeReqDTOList){
            NewsCodeRespVO newsCodeRespVO = new NewsCodeRespVO();
            IndustrySw industrySw = industrySwService.queryByCode(newsCodeReqDTO.getIndustryCode());
            newsCodeRespVO.setNewsNum(newsCodeReqDTO.getNewsNum());
            newsCodeRespVO.setIndustryCode(newsCodeReqDTO.getIndustryCode());
            newsCodeRespVO.setIndustryId(industrySw.getId());
            newsCodeRespVO.setIndustryName(industrySw.getName());
            newsCodeRespVO.setCreateTime(industrySw.getCreateTime());
            newsCodeRespVOList.add(newsCodeRespVO);
        }

        return newsCodeRespVOList;
    }


    @ApiOperation("查询情感色彩的行业资讯")
    @PostMapping("/queryNews-sentiment")
    public ResponseInfo<List<NewsSentimentRespVO>> queryNewsSentiment() {
        log.info("NewsController.queryNewsSentiment start...");
        List<NewsSentimentRespDTO> newsSentimentRespDTOList = appNewsService.queryNewsSentiment();
        List<NewsSentimentRespVO> newsSentimentRespVOS = new ArrayList<>();
        if(newsSentimentRespDTOList.size() > 0){
            for(NewsSentimentRespDTO newsSentimentRespDTO : newsSentimentRespDTOList){
                NewsSentimentRespVO newsSentimentRespVO = new NewsSentimentRespVO();
                BeanUtils.copyProperties(newsSentimentRespDTO,newsSentimentRespVO);
                if (Constant.SENTIMENT_POSITIVE.equals(newsSentimentRespDTO.getSentimentCode())) {
                    newsSentimentRespVO.setSentimentName("积极");
                }
                if (Constant.SENTIMENT_NEUTRAL.equals(newsSentimentRespDTO.getSentimentCode())) {
                    newsSentimentRespVO.setSentimentName("中立");
                }
                if (Constant.SENTIMENT_NEGATIVE.equals(newsSentimentRespDTO.getSentimentCode())) {
                    newsSentimentRespVO.setSentimentName("消极");
                }
                newsSentimentRespVOS.add(newsSentimentRespVO);
            }
        }

        return new ResponseInfo<>(newsSentimentRespVOS);
    }


}
